package hxy.bytecode.net;

import java.io.*;
import java.net.Socket;

/**
 * @author eric
 * @program bytecode
 * @description http的get方法测试
 * @date 2020/4/26
 */
public class HttpGet {
    public static void main(String[] args) {

        int port=8763;

        String data = "{\"name\":\"star\"}";
        StringBuffer sb = new StringBuffer("GET /detect_list/ HTTP/1.1\r\n");
        sb.append("Host: localhost:"+String.valueOf(port)+"\r\n");
        sb.append("Content-Type: application/json;charset=UTF-8\r\n");
        try {
            sb.append("Content-Length: "+data.getBytes("utf-8").length+"\r\n");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.append("Connection: close\r\n");
        sb.append("\r\n");
        sb.append(data);
        System.out.println("\n===>请求消息报文：\n"+sb.toString());
        System.out.println("\n===>发起请求接收信息");
        try(Socket socket = new Socket("localhost",port)) {
            OutputStream os = socket.getOutputStream();
            os.write(sb.toString().getBytes("utf-8"));
            os.flush();
            InputStream is =  socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while(br.readLine() != null){
                System.out.println(br.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
